package com.zhugang.week06;

/**
 * @program algorithms
 * @description: isValidBST
 * @author: chanzhugang
 * @create: 2022/07/18 11:17
 */
public class IsValidBST {

    /**
     * 98 验证二叉搜索树
     *
     * @param root
     * @return
     */
    private boolean isValid = true;

    public boolean isValidBST(TreeNode root) {
        // 转化为递归求二叉树的最大值、最小值
        if (root == null) {
            return true;
        }
        dfs(root);
        return isValid;
    }

    /**
     * 求二叉树最大值、最小值，顺便验证是否是二叉搜索树
     *
     * @param root
     * @return
     */
    private int[] dfs(TreeNode root) {
        int min = root.val;
        int max = root.val;
        if (root.left != null) {
            int[] leftMinMax = dfs(root.left);
            if (isValid == false) {
                return null;
            }
            if (leftMinMax[1] >= root.val) {
                isValid = false;
                return null;
            }
            min = leftMinMax[0];
        }

        if (root.right != null) {
            int[] rightMinMax = dfs(root.right);
            if (isValid == false) {
                return null;
            }
            if (rightMinMax[0] <= root.val) {
                isValid = false;
                return null;
            }
            max = rightMinMax[1];
        }
        return new int[]{min, max};
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}